#include "downloadFile.h"

bool downloadFilePage::response(std::string pathArg)
{
    //HTML Start
    out<<LR"(
        <!DOCTYPE html>
        <html xmlns:svg="http://www.w3.org/2000/svg">
            <head>
                <meta charset="utf-8" />
                <title>服务器文件管理</title>
                <meta name="viewport" content="width=device-width, initial-scale=1">
                <link href="https://cdn.staticfile.org/twitter-bootstrap/5.1.1/css/bootstrap.min.css" rel="stylesheet">
                <script src="https://cdn.staticfile.org/twitter-bootstrap/5.1.1/js/bootstrap.bundle.min.js"></script>
                <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
                <script>
                    "use strict";
    )";
                    out<<fmt::format(L"let currentPath='{}'; ",std::wstring_convert<std::codecvt_utf8<wchar_t>>().from_bytes(pathArg));
    out<<LR"+(
                    function openDir(fileName)
                    {
                        window.open("fileBrowser"+"?path="+currentPath+fileName+"/","_self");
                    }
                    function downloadFile(fileName)
                    {
                        window.location.href="fileDownload"+"?path="+currentPath+fileName;
                    }

                    function selectedFileChanged()
                    {
                        let selectBtn=document.getElementById("selectFileBtn");
                        if(selectBtn.files.length==0)
                        {
                            return;
                        }
                        let fileName=selectBtn.files[0].name;
                        const reader=new FileReader();
                        reader.onload=function fileReadCompleted()
                        {
                            let ajax=new XMLHttpRequest();
                            ajax.open("POST","fileUpload",true);
                            console.log(currentPath+fileName);
                            ajax.setRequestHeader("Upload-Path",btoa(encodeURIComponent(currentPath+fileName)));
                            ajax.onreadystatechange=function()
                            {
                                if ( XMLHttpRequest.DONE != ajax.readyState ) 
                                {
                                    return;
                                }
                                if(ajax.status == 200)
                                {
                                    console.log("Update Success!");
                                    
                                }
                                else
                                {
                                    console.log("File Upload ERROR "+ajax.status);
                                }
                                return;
                            };

                            ajax.send(new DataView(reader.result));
                            return;
                        };
                        reader.readAsArrayBuffer(selectBtn.files[0]);
                    }

                    function DeleteFile()
                    {
                        let fileLists=document.getElementsByName("fileList");
                        for(let singleItem of fileLists)
                        {
                            if(singleItem.checked)
                            {
                                let text=currentPath+singleItem.getAttribute("data-fileName");
                                console.log(text);
                                let ajax=new XMLHttpRequest();
                                ajax.open("POST","fileDelete",true);
                                ajax.onreadystatechange=function()
                                {
                                    if ( XMLHttpRequest.DONE != ajax.readyState ) 
                                    {
                                        return;
                                    }
                                    if(ajax.status == 200)
                                    {
                                        console.log("Delete Success!");
                                    }
                                    else
                                    {
                                        console.log("File Delete ERROR "+ajax.status);
                                    }
                                    return;
                                }
                                ajax.send(text);
                            }
                        }
                    }

                    function RenameFile()
                    {
                        let fileLists=document.getElementsByName("fileList");
                        if(fileLists.length>0)
                        {
                            let currentFile=fileLists[0];
                            let ajax=new XMLHttpRequest();
                            ajax.open("POST","fileRename",true);
                            ajax.onreadystatechange=function()
                            {
                                if ( XMLHttpRequest.DONE != ajax.readyState ) 
                                {
                                    return;
                                }
                                if(ajax.status == 200)
                                {
                                    console.log("Rename Success!");
                                }
                                else
                                {
                                    console.log("File Rename ERROR "+ajax.status);
                                }
                                return;
                            }
                            let renameJSON={
                                Path : currentPath+currentFile.getAttribute("data-fileName"), 
                                NewName : currentPath+document.getElementsByName("rename_newText")[0].value
                            };
                            ajax.send(JSON.stringify(renameJSON));
                        }
                    }
                </script>
            </head>
            <body>
                <div class="container-fluid p-4 bg-dark text-white">
                    <h1>文件传输助手</h1>
                </div>
                <div class="row m-1">
                    <button class="col-1 mx-1 btn btn-outline-primary" type="button" data-bs-toggle="modal" data-bs-target="#uploadFileModal">上传文件</button>
                    <button class="col-1 mx-1 btn btn-outline-primary">下载文件</button>
                    <button class="col-1 mx-1 btn btn-outline-primary" type="button" data-bs-toggle="modal" data-bs-target="#renameModal">重命名</button>
                    <button class="col-1 mx-1 btn btn-outline-primary" onclick="location.reload()">刷新</button>
                    <button class="col-1 mx-1 btn btn-outline-primary" onclick="DeleteFile()">删除</button>
                </div>
                <div class="container-fluid">
                    <ul class="pagination"> 
    )+";
                        getPath(pathArg);
    out<<LR"(
                    </ul>
                </div>
                <div class="container-fluid mx-3"> 
                    <table class="table table-hover">
                        <thead>
                            <tr>
                                <th>选择</th>
                                <th>文件类型</th>
                                <th>文件名</th>
                                <th>操作</th>
                            </tr>
                        </thead>
                        <tbody>
    )";
                            getDirectory(nowPath);
    out<<LR"+(
                        </tbody>
                    </table>
                </div>
                <div class="modal fade" id="uploadFileModal">
                    <div class="modal-dialog">
                        <div class="modal-content">
                            <div class="modal-header">
                                <h4 class="modal-title">上传文件</h4>
                                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                            </div>
                            <div class="modal-body">
                                    <p>选择文件</p>
                                    <input type="file" id="selectFileBtn" onChange="selectedFileChanged()">
                            </div>
                        </div>
                    </div>
                </div>

                <!-- 重命名 -->
                <div class="modal fade" id="renameModal">
                    <div class="modal-dialog">
                        <div class="modal-content">
                            <div class="modal-header">
                                <h4 class="modal-title">重命名文件</h4>
                                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                            </div>
                            <div class="modal-body">
                                <input type="text" name="rename_newText">
                                <button type="button" class="btn btn-primary" onclick="RenameFile()">重命名</button>
                            </div>
                            <div class="modal-footer">
                            </div>
                        </div>
                    </div>
                </div>
            </body>
        </html>
    )+";

    return true;
}

std::wstringstream& downloadFilePage::getOutputString()
{
    return out;
}

void downloadFilePage::getDirectory(std::string DirPath)
{
    
    auto outHTML_td=[this](std::string str)
    {
        std::wstring_convert<std::codecvt_utf8<wchar_t>> charConvert;
        out<<LR"( <td> )";
        out<<charConvert.from_bytes(str);
        out<<LR"( </td> )";
    };
    std::filesystem::path path_(DirPath);
    if(!std::filesystem::exists(path_))
        return;
    std::filesystem::directory_entry entry(path_);
    if(entry.status().type()==std::filesystem::file_type::directory)
    {
        
        std::filesystem::directory_iterator list(path_);
        for(auto& i:list)
        {
            std::string fileName=i.path().filename();
            out<<R"( <tr> )";
            outHTML_td(fmt::format(R"(<input class="form-check-input col-1" name="fileList" type="checkbox" value="文件1" data-fileName="{}"></input>)",fileName));
            switch (std::filesystem::status(i.path()).type())
            {
                case std::filesystem::file_type::none : outHTML_td(R"( <p>None</p> )"); break;
                case std::filesystem::file_type::not_found : outHTML_td(R"( <p>NotFound</p> )"); break;
                case std::filesystem::file_type::regular : outHTML_td(R"( <p>Regular</p> )"); break;
                case std::filesystem::file_type::directory : outHTML_td(R"( <p>Directory</p> )"); break;
                case std::filesystem::file_type::symlink : outHTML_td(R"( <p>Symlink</p> )"); break;
                case std::filesystem::file_type::block : outHTML_td(R"( <p>Block</p> )"); break;
                case std::filesystem::file_type::character : outHTML_td(R"( <p>Character</p> )"); break;
                case std::filesystem::file_type::fifo : outHTML_td(R"( <p>Fifo</p> )"); break;
                case std::filesystem::file_type::socket : outHTML_td(R"( <p>Socket</p> )"); break;
                default : outHTML_td(R"( <p>Unknow</p> )"); break;
            }
            outHTML_td(fmt::format(R"( <p>{}</p> )",fileName));
            switch (std::filesystem::status(i.path()).type())
            {
                case std::filesystem::file_type::regular : outHTML_td(fmt::format(R"+( <button type="button" class="btn btn-primary" onclick="downloadFile('{}')">下载文件</button> )+",fileName)); break;
                case std::filesystem::file_type::directory : outHTML_td(fmt::format(R"+( <button type="button" class="btn btn-primary" onclick="openDir('{}')">打开文件夹</button> )+",fileName)); break;
                default :  break;
            }
            out<<LR"( </tr> )";
        }
    }
}

void downloadFilePage::getPath(std::string para)
{
    auto subPath=[this](std::string path)
    {
        nowPath.clear();
        std::size_t Ipos=0;
        std::size_t IposLast=0;
        while ( true )
        {
            Ipos=path.find('/',Ipos);
            if(Ipos==std::string::npos)
                break;
            nowPath+=path.substr(IposLast,Ipos-IposLast+1);
            std::string convertBuff=fmt::format(R"( <li class="page-item"><a class="page-link" href="http://192.168.137.3:8510/fileBrowser?path={}">{}</a></li> )",nowPath,path.substr(IposLast,Ipos-IposLast+1));
            out<<std::wstring_convert<std::codecvt_utf8<wchar_t>>().from_bytes(convertBuff);
            IposLast=++Ipos;
        }
    };
    subPath(para);
}

